package ru.mipt.board.net
import scala.actors._
import ru.mipt.board.DB._


/**
 * Created by IntelliJ IDEA.
 * User: IL
 * Date: 19.09.2010
 * Time: 14:40:52
 * To change this template use File | Settings | File Templates.
 */

//messages

class start{}
class end{}

class MainActor extends Actor with DBuser{
    val users = new scala.collection.mutable.HashSet[String]
    val numPosts = 7777000
    val numWorkers = 25//TODO change back
    val step = numPosts / numWorkers
    val downloadedPosts = new Array[Boolean](numPosts).map(a => false)//init to false
    val workers = new Array[WorkingActor](numWorkers).map (a => new WorkingActor)
    workers foreach  {a => a.start; /*getTask(a)*/ }

    def act={
        loop{
            receive{
                case a:start =>   workers foreach  { getTask(_) }
                case a:end => ;
                case (messages: List[BoardMessage],callback: Actor) => process(messages, callback)
                case _ =>  println("main actor recived unknown message")
            }
        }
    }

    def process(messages: List[BoardMessage], callback: Actor) = {
        try {
            for (boardMessage <- messages) {
                if (!(users contains boardMessage.username)) users add boardMessage.username
                downloadedPosts(boardMessage.ID - 1) = true
            }
            insertMessages(messages)
        }
        catch{
            case ex => println("exception in main actor process" + ex)
        }
        finally {  getTask(callback)  }
    }

    def getTask(callback: Actor): Unit = {
        val start = (workers indexOf callback)*step
        val nextThread =  downloadedPosts.indexOf(false,start)//send next free post from his area
        if(nextThread == -1) return ();
        downloadedPosts(nextThread) = true
        callback ! (nextThread + 1,this)//Arrays are indexed from 0
    }
}
